import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../models/service_item.dart';
import 'service_item_widget.dart';
import 'add_service_dialog.dart';
import '../theme/app_colors.dart';

class ServiceListWidget extends StatelessWidget {
  final List<ServiceItem> services;
  final Function(ServiceItem, bool) onServiceToggle;
  final bool Function() canEnableMoreServices;
  final VoidCallback onUpgradeRequired;
  final VoidCallback? onRefresh;
  final Function(String, int)? onAddServer;
  final bool isLoading;
  final String? errorMessage;
  final Set<String> loadingServices;
  final Function(ServiceItem)? onServiceEdit; // 新增编辑回调
  final Function(ServiceItem)? onServiceDelete; // 新增删除回调

  const ServiceListWidget({
    super.key,
    required this.services,
    required this.onServiceToggle,
    required this.canEnableMoreServices,
    required this.onUpgradeRequired,
    this.onRefresh,
    this.onAddServer,
    this.isLoading = false,
    this.errorMessage,
    this.loadingServices = const {},
    this.onServiceEdit,
    this.onServiceDelete,
  });

  // 显示添加服务对话框
  void _showAddServiceDialog(BuildContext context) {
    showDialog<bool>(
      context: context,
      builder: (context) => const AddServiceDialog(),
    ).then((result) {
      if (result == true && onRefresh != null) {
        onRefresh!();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final isSmallScreen = MediaQuery.of(context).size.width < 600;
    final headerHeight = isSmallScreen ? 56.0 : 64.0; // 标题行固定高度

    return LayoutBuilder(
      builder: (context, constraints) {
        return Container(
          decoration: BoxDecoration(
            color: Theme.of(context).scaffoldBackgroundColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              // 固定在顶部的标题行
              Container(
                height: headerHeight,
                padding: EdgeInsets.all(isSmallScreen ? 8 : 12),
                decoration: BoxDecoration(
                  color: Theme.of(context).cardColor,
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(8),
                    topRight: Radius.circular(8),
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        AppLocalizations.of(context)!.serviceList,
                        style: TextStyle(
                          color: Theme.of(context).textTheme.titleLarge?.color,
                          fontSize: isSmallScreen ? 18 : 20,
                          fontWeight: FontWeight.bold,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    IconButton(
                      icon: Icon(
                        Icons.add,
                        color: Theme.of(context).textTheme.bodyMedium?.color,
                        size: isSmallScreen ? 24 : 28,
                      ),
                      onPressed: () => _showAddServiceDialog(context),
                      constraints: BoxConstraints(
                        minWidth: isSmallScreen ? 40 : 48,
                        minHeight: isSmallScreen ? 40 : 48,
                      ),
                      padding: EdgeInsets.all(isSmallScreen ? 4 : 6),
                    ),
                    IconButton(
                      icon: Icon(
                        Icons.refresh,
                        color: isLoading
                            ? Theme.of(context).disabledColor
                            : Theme.of(context).textTheme.bodyMedium?.color,
                        size: isSmallScreen ? 24 : 28,
                      ),
                      onPressed: isLoading ? null : onRefresh,
                      constraints: BoxConstraints(
                        minWidth: isSmallScreen ? 40 : 48,
                        minHeight: isSmallScreen ? 40 : 48,
                      ),
                      padding: EdgeInsets.all(isSmallScreen ? 4 : 6),
                    ),
                  ],
                ),
              ),
              // 内容区域 - 使用Expanded确保占满剩余空间且可滚动
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).cardColor,
                    borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(8),
                      bottomRight: Radius.circular(8),
                    ),
                  ),
                  child: ListView(
                    padding: EdgeInsets.fromLTRB(
                      isSmallScreen ? 12 : 16,
                      isSmallScreen ? 8 : 12,
                      isSmallScreen ? 12 : 16,
                      isSmallScreen ? 16 : 24, // 增加底部padding，确保最后一项不被遮挡
                    ),
                    physics: const AlwaysScrollableScrollPhysics(), // 确保始终可以滚动
                    children: [
                      // 错误信息显示
                      if (errorMessage != null)
                        Container(
                          margin: const EdgeInsets.only(bottom: 12),
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: AppColors.of(context).error.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: AppColors.of(context).error.withOpacity(0.3),
                            ),
                          ),
                          child: Row(
                            children: [
                              Icon(
                                Icons.error_outline,
                                color: AppColors.of(context).error,
                                size: 18,
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Text(
                                  errorMessage!,
                                  style: TextStyle(
                                    color: AppColors.of(context).error,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      // 加载状态或服务列表
                      if (isLoading)
                        Container(
                          height: 120,
                          child: Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const SizedBox(
                                  width: 24,
                                  height: 24,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                  ),
                                ),
                                const SizedBox(height: 12),
                                Text(
                                  AppLocalizations.of(context)!.loading,
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Theme.of(
                                      context,
                                    ).textTheme.bodyMedium?.color,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      else if (services.isEmpty)
                        Container(
                          height: 120,
                          child: Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.dns_outlined,
                                  size: 48,
                                  color: Theme.of(
                                    context,
                                  ).textTheme.bodyMedium?.color,
                                ),
                                const SizedBox(height: 12),
                                Text(
                                  AppLocalizations.of(context)!.noServices,
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Theme.of(
                                      context,
                                    ).textTheme.bodyMedium?.color,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      else
                        ...services.asMap().entries.map((entry) {
                          final index = entry.key;
                          final service = entry.value;
                          return Container(
                            margin: EdgeInsets.only(
                              bottom: index == services.length - 1
                                  ? 0
                                  : 8, // 最后一项不添加底部间距
                            ),
                            child: ServiceItemWidget(
                              service: service,
                              onToggle: (value) =>
                                  onServiceToggle(service, value),
                              onUpgradeRequired: onUpgradeRequired,
                              canEnableMoreServices: canEnableMoreServices,
                              isLoading: loadingServices.contains(service.id),
                              onEdit: onServiceEdit,
                              onDelete: onServiceDelete,
                              onRefresh: onRefresh,
                            ),
                          );
                        }).toList(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
